package com.fufu.mq.direct;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 生产者:直连交换机模式
 */
public class ProducerDirect {

    public static void main(String[] args) throws Exception {

        String exchangeName = "my-first-exchange";

        String queueName1 = "my-first-queue1";
        String queueName2 = "my-first-queue2";
        String queueName3 = "my-first-queue3";
        String queueName4 = "my-first-queue4";

        String routingKey1 = "my-first-routingkey1";
        String routingKey2 = "my-first-routingkey2";
        String routingKey3 = "my-first-routingkey3";
        String routingKey4 = "my-first-routingkey4";

        // 创建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 服务地址
        factory.setHost("localhost");
        // 端口号
        factory.setPort(5672);
        // 用户名
        factory.setUsername("guest");
        // 密码
        factory.setPassword("guest");

        // 新建连接
        Connection connection = factory.newConnection();
        // 创建信道
        Channel channel = connection.createChannel();
        // 连接交换机
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,null);

        // 连接队列
        channel.queueDeclare(queueName1,true,false,false,null);
        channel.queueDeclare(queueName2,true,false,false,null);
        channel.queueDeclare(queueName3,true,false,false,null);
        channel.queueDeclare(queueName4,true,false,false,null);

        // 交换机和队列绑定
        channel.queueBind(queueName1,exchangeName,routingKey1);
        channel.queueBind(queueName2,exchangeName,routingKey2);
        channel.queueBind(queueName3,exchangeName,routingKey3);
        channel.queueBind(queueName4,exchangeName,routingKey4);

        String message = "Hello World!";
        // 发送消息
        channel.basicPublish(exchangeName,routingKey1,null,message.getBytes());
        channel.basicPublish(exchangeName,routingKey2,null,message.getBytes());
        channel.basicPublish(exchangeName,routingKey3,null,message.getBytes());
        channel.basicPublish(exchangeName,routingKey4,null,message.getBytes());


        channel.close();
        connection.close();
        System.out.println("消息已发送");
    }
}
